<template>
    <el-card style="height: 80px">
      <el-form :inline="true" class="form">
        <el-form-item label="用户名:">
          <el-input v-model="searchName" placeholder="请你输入搜索用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" class="blue-border-button search-reset-button" @click="handleSearch">搜索</el-button>
          <el-button type="primary" size="default" class="blue-border-button search-reset-button" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0px">
      <el-button type="primary" size="default" class="blue-border-button" @click="dialogVisible = true">添加用户</el-button>
      <!-- <el-button type="primary" size="default" class="blue-border-button">批量删除</el-button> -->
      <!-- table展示用户信息 -->
      <el-table :data="userList" style="margin: 10px 0px" border v-loading="loading">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column label="#" align="center" type="index"></el-table-column>
        <el-table-column prop="userId" label="ID" align="center"></el-table-column>
        <el-table-column
          prop="userName"
          label="用户名字"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="nickName"
          label="用户名称"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="roles"
          label="用户角色"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          show-overflow-tooltip
        >
          <template #default="{row}">
            {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          align="center"
          show-overflow-tooltip
        >
          <template #default="{row}">
            {{ dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="300px"
          align="center"
        >
          <template #default="{row}">
            <el-button 
              type="primary" 
              size="small" 
              class="blue-border-button"
              @click="handleEdit(row)"
            >
              修改
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              class="blue-border-button"
              @click="handleDelete(row.userId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="pageNo"
        :page-size="10"
        :background="true"
        layout="prev, pager, next, jumper, total"
        :total="allUserList.length"
      />
    </el-card>
    
    <!-- 添加用户对话框 - 位于页面底部，点击"添加用户"按钮后弹出 -->
    <el-dialog v-model="dialogVisible" title="添加用户" width="30%" @close="resetAddForm">
      <el-form :model="addForm" :rules="rules" label-width="80px">
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="addForm.nickName" placeholder="请输入用户昵称"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="addForm.phonenumber" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="addForm.sex" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="0"></el-option>
            <el-option label="女" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddUser">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改用户" width="30%">
      <el-form :model="editForm" :rules="rules" label-width="80px">
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="editForm.nickName" placeholder="请输入用户昵称"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="editForm.phonenumber" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" placeholder="请输入新密码(留空不修改)" show-password></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="editForm.sex" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" value="0"></el-option>
            <el-option label="女" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleModify">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { reqUserFind, reqAddUser, reqModifyUser, reqDeleteUser } from '@/api/user'
import dayjs from 'dayjs'

// 对话框状态
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const currentEditUser = ref<any>(null)
const addForm = ref({
  nickName: '',
  phonenumber: '',
  userName: '',
  password: '',
  sex: '',
  email: ''
})

const editForm = ref({
  nickName: '',
  phonenumber: '',
  userName: '',
  password: '',
  sex: '',
  email: ''
})
const rules = {
  nickName: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }],
  phonenumber: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
  ]
}

const userList = ref<any[]>([])
const loading = ref(false)
const pageNo = ref(1)
const pageSize = 10
const searchName = ref('')

const handleSearch = () => {
  pageNo.value = 1
  getUser()
}

const reset = () => {
  searchName.value = ''
  pageNo.value = 1
  // pageSize is fixed at 10
  getUser()
}

const allUserList = ref<any[]>([])

const getUser = async() => {
  try {
    loading.value = true
    const params = searchName.value ? { userName: searchName.value } : {}
    const result = await reqUserFind(params)
    if(result.code === 0) {
      allUserList.value = result.data
      // 前端分页处理
      const start = (pageNo.value - 1) * pageSize
      const end = start + pageSize
      userList.value = allUserList.value.slice(start, end)
    } else {
      ElMessage.error('获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error('请求异常')
  } finally {
    loading.value = false
  }
}

// 监听分页变化
watch(pageNo, () => {
  getUser()
})
// 添加用户
const resetAddForm = () => {
  addForm.value = {
    nickName: '',
    phonenumber: '',
    userName: '',
    password: '',
    sex: '',
    email: ''
  }
}

const handleAddUser = async () => {
  try {
    loading.value = true
    const result = await reqAddUser(addForm.value)
    if (result.code === 0) {
      ElMessage.success('添加用户成功')
      dialogVisible.value = false
      resetAddForm()
      // 刷新用户列表
      getUser()
    } else {
      ElMessage.error(result.message || '添加用户失败')
    }
  } catch (error) {
    ElMessage.error('请求异常')
  } finally {
    loading.value = false
  }
}

// 修改用户
const handleEdit = (user: any) => {
  currentEditUser.value = user
  editForm.value = {
    nickName: user.nickName,
    phonenumber: user.phonenumber,
    userName: user.userName,
    password: '',
    sex: user.sex,
    email: user.email
  }
  editDialogVisible.value = true
}

const handleModify = async () => {
  try {
    loading.value = true
    const result = await reqModifyUser({
      ...editForm.value,
      userId: currentEditUser.value.userId
    })
    if (result.code === 0) {
      ElMessage.success('修改用户成功')
      editDialogVisible.value = false
      getUser()
    } else {
      ElMessage.error(result.message || '修改用户失败')
    }
  } catch (error) {
    ElMessage.error('请求异常')
  } finally {
    loading.value = false
  }
}

// 删除用户
const handleDelete = async (userId: string) => {
  try {
    loading.value = true
    const result = await reqDeleteUser({ userId })
    if (result.code === 0) {
      ElMessage.success('删除用户成功')
      getUser()
    } else {
      ElMessage.error(result.message || '删除用户失败')
    }
  } catch (error) {
    ElMessage.error('请求异常')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getUser()
})
</script>

<style scoped>
.blue-border-button {
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 14px;
  min-width: 100px;
  transition: all 0.3s ease;
  
  &:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  }
  
  &:active {
    background-color: #3a8ee6;
    border-color: #3a8ee6;
    transform: translateY(0);
    box-shadow: none;
  }
}

.search-reset-button {
  padding: 8px 16px;
  min-width: 80px;
}
</style>
